from pathlib import Path 
import logging 

from .config import get_settings 

settings = get_settings()


ROOT_DIR = settings.root_dir
FIND_DIR = settings.find_dir

logger = logging.getLogger(__name__)

file_names: list[str] = []
change_status = False 


# 重命名文件
def rename(path: Path) -> None: 
    global change_status
    # 判断文件是否有子文件，如果有子文件则重新命名 
    file_status = any(path.iterdir())
    if not file_status : 
        return 
    
    change_status = True 
    file_name = path.stem 

    if file_name[-1:] != '待': 
        file_names.append(file_name)
        return 
    
    
    # 获取文件名称以及更改
    name = path.parent / path.stem[:-2]
    
    new_name = path.rename(name)
    
    file_names.append(new_name.stem)


# 这个函数在查找文件模块也用了
def get_path() -> Path | None: 
    p = Path(__file__).parents[1] / ROOT_DIR
    
    if FIND_DIR: 
        return p / FIND_DIR 

    if not p.exists(): 
        return 
    if not any(p.iterdir()): 
        return 
    
    path_dir: dict = {}
    
    for d in p.iterdir(): 
       
        # 获取创建时间 
        status = d.stat()
        create_time = status.st_mtime 
        path_dir[create_time] = d 

    k = max(path_dir)
    return path_dir[k]

    

def main() -> None: 
    path = get_path() 
    if not path: 
       
        print('没有文件。。。')
        return 
    
    filename = path / 'alter.log'


    logging.basicConfig(filename=filename, encoding='utf-8',
                        level=logging.INFO, format=settings.format)

    logger.info('*********************')

    par_dir = [p for p in path.iterdir() if p.is_dir()]
    for sub_dir in par_dir: 
        for i in sub_dir.iterdir(): 
            rename(i)
    
    if not change_status: 
        logger.info('没有更改任何文件')
    else:
        logger.info('可以使用的文件如下:')
        logger.info('\n'.join(file_names))

if __name__ == '__main__': 
    main()

